package com.sc.common.util;

import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class WebUtils {
    public static final String PC = "pc";
    public static final String ANDROID = "Android";
    public static final String IPHONE = "IPhone";
    public static final String IPAD = "IPad";
    public static final String WINDOWS_PHONE = "Windows Phone";
    public static final String IPOD = "IPod";
    public static final String DEFAULT_JSON_FILTER_NAME = "s2jhFilter";
    private static final Logger LOG = LoggerFactory.getLogger(WebUtils.class);
    private static final SimpleFilterProvider serializeAllFilterProvider = (new SimpleFilterProvider()).addFilter("s2jhFilter", SimpleBeanPropertyFilter.serializeAllExcept(new String[0]));
    private static final ThreadLocal<SimpleBeanPropertyFilter> simpleBeanPropertyFilterContainer = new ThreadLocal();

    public WebUtils() {
    }

    public static int getParam(HttpServletRequest request, String param, int defaultValue) {
        try {
            String value = request.getParameter(param);
            return Integer.parseInt(value);
        } catch (Exception var4) {
            return defaultValue;
        }
    }

    public static Object getParamForSession(HttpServletRequest request, String param, Object defaultValue) {
        try {
            Object value = request.getSession().getAttribute(param);
            return value;
        } catch (Exception var4) {
            return defaultValue;
        }
    }

    public static long getParam(HttpServletRequest request, String param, long defaultValue) {
        try {
            String value = request.getParameter(param);
            return Long.parseLong(value);
        } catch (Exception var5) {
            return defaultValue;
        }
    }

    public static boolean getParam(HttpServletRequest request, String param, boolean defaultValue) {
        try {
            String value = request.getParameter(param);
            return Boolean.parseBoolean(value);
        } catch (Exception var4) {
            return defaultValue;
        }
    }

    public static float getParam(HttpServletRequest request, String param, float defaultValue) {
        try {
            String value = request.getParameter(param);
            return Float.parseFloat(value);
        } catch (Exception var4) {
            return defaultValue;
        }
    }

    public static String getParam(HttpServletRequest request, String param, String defaultValue) {
        String value = request.getParameter(param);
        if (value != null) {
            value = value.trim();
        }

        return StringUtils.isBlank(value) ? defaultValue : value;
    }

    public static String getUTF8Value(HttpServletRequest request, String param) {
        String value = request.getParameter(param);
        return decodeParam(value, "UTF-8");
    }

    public static String decodeParam(String value, String charset) {
        try {
            if (StringUtils.isNotBlank(value)) {
                return new String(value.getBytes("ISO-8859-1"), charset);
            }
        } catch (UnsupportedEncodingException var3) {
            LOG.error(var3.getMessage(), var3);
        }

        return null;
    }

    public static String getCookieValue(HttpServletRequest request, String cookieName) {
        Assert.notNull(request);
        Assert.hasText(cookieName);
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            Cookie[] arr = cookies;
            int len = cookies.length;

            for(int i = 0; i < len; ++i) {
                Cookie cookie = arr[i];
                if (cookie != null && cookie.getName() != null && cookie.getName().equals(cookieName)) {
                    String rValue = decode(cookie.getValue());
                    return rValue;
                }
            }
        }

        return null;
    }

    public static void setCookieValue(HttpServletResponse response, String cookieName, String value, String domain, int cookieAge) {
        setCookieValue(response, cookieName, value, domain, cookieAge, (String)null);
    }

    public static void setCookieValue(HttpServletResponse response, String cookieName, String value, String domain, int cookieAge, String cookiePath) {
        Assert.notNull(response);
        Assert.hasText(cookieName);
        Assert.hasText(value);
        value = encode(value);
        Cookie cookie = new Cookie(cookieName, value);
        if (StringUtils.isBlank(cookiePath)) {
            cookie.setPath("/");
        } else {
            cookie.setPath(cookiePath);
        }

        cookie.setDomain(domain);
        cookie.setMaxAge(cookieAge);
        response.addCookie(cookie);
    }

    public static String getHost(String url) {
        try {
            String s = url;
            int pos = url.indexOf("//");
            if (pos > -1) {
                s = url.substring(pos + 2);
            }

            pos = s.indexOf("/");
            if (pos > -1) {
                s = s.substring(0, pos);
            }

            if (s.trim().length() == 0) {
                s = "";
            }

            return s;
        } catch (Exception var3) {
            return "";
        }
    }

    public static void deleteCookie(String domain, HttpServletRequest request, HttpServletResponse response, String... cookieNames) {
        deleteCookie(domain, (String)null, request, response, cookieNames);
    }

    public static void deleteCookie(String domain, String path, HttpServletRequest request, HttpServletResponse response, String... cookieNames) {
        Assert.notNull(request);
        path = path != null && !path.equals("") ? path : "/";
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            Cookie[] arr$ = cookies;
            int len$ = cookies.length;

            for(int i$ = 0; i$ < len$; ++i$) {
                Cookie cookie = arr$[i$];
                String[] arr = cookieNames;
                int len = cookieNames.length;

                for(int i = 0; i < len; ++i) {
                    String cookieName = arr[i];
                    Assert.hasText(cookieName);
                    if (cookie.getName().equals(cookieName)) {
                        cookie.setPath(path);
                        cookie.setMaxAge(0);
                        cookie.setDomain(domain);
                        response.addCookie(cookie);
                        break;
                    }
                }
            }
        }

    }

    public static void deleteAllCookies(HttpServletRequest request, HttpServletResponse response, String domain) {
        Assert.notNull(request);
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            Cookie[] arr = cookies;
            int len = cookies.length;

            for(int i = 0; i < len; ++i) {
                Cookie cookie = arr[i];
                if (cookie.getDomain() != null && cookie.getDomain().equals(domain)) {
                    cookie.setPath(cookie.getPath());
                    cookie.setMaxAge(0);
                    cookie.setDomain(cookie.getDomain());
                    response.addCookie(cookie);
                }
            }
        }

    }
/*
    public static void writeJson(Object obj, HttpServletRequest request, HttpServletResponse response) {
        writeJson(obj, request, response, (Map)null);
    }*/



  /*  public static void writeJson(Object obj, HttpServletRequest request, HttpServletResponse response, Map<Class, JsonSerializer> serializerMap) {
        try {
            String callBack = ServletRequestUtils.getStringParameter(request, "callback");
            response.setHeader("Content-Language", "zh-cn");
            response.setHeader("Cache-Control", "no-cache");
            response.setContentType("application/json; charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            String result = null;
            if (obj instanceof String) {
                result = obj.toString();
            } else {
                GsonBuilder builder = (new GsonBuilder()).setExclusionStrategies(new ExclusionStrategy[]{new FieldIgnoreGsonStrategy()});
                if (serializerMap != null && !serializerMap.isEmpty()) {
                    Iterator i = serializerMap.entrySet().iterator();

                    while(i.hasNext()) {
                        Map.Entry<Class, JsonSerializer> entry = (Map.Entry)i.next();
                        builder.registerTypeHierarchyAdapter((Class)entry.getKey(), entry.getValue());
                    }
                }

                result = builder.create().toJson(obj);
            }

            if (StringUtils.isNotBlank(callBack)) {
                result = callBack + "(" + result + ")";
            }

            response.getWriter().write(result);
        } catch (IOException var9) {
            LOG.error(var9.getMessage(), var9);
        } catch (ServletRequestBindingException var10) {
            LOG.error("[写json时候异常]" + obj + ", ip:" + getIpAddr(request), var10);
        }

    }*/

   /* public static void writeJsonForJPA(Object obj, HttpServletRequest request, HttpServletResponse response) {
        try {
            ObjectMapper mapper = HibernateAwareObjectMapper.getInstance();
            response.setHeader("Content-Language", "zh-cn");
            response.setHeader("Cache-Control", "no-cache");
            response.setContentType("application/json; charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            String msg;
            if (obj instanceof Throwable) {
                Throwable tr = (Throwable)obj;
                msg = tr.getMessage();
                Map<String, String> errors = Maps.newHashMap();
                errors.put("type", "error");
                errors.put("message", msg);
                mapper.writeValue(response.getWriter(), errors);
            } else {
                SimpleBeanPropertyFilter simpleBeanPropertyFilter = (SimpleBeanPropertyFilter)simpleBeanPropertyFilterContainer.get();
                msg = null;
                SimpleFilterProvider filters;
                if (simpleBeanPropertyFilter != null) {
                    filters = (new SimpleFilterProvider()).addFilter("s2jhFilter", simpleBeanPropertyFilter);
                } else {
                    filters = serializeAllFilterProvider;
                }

                mapper.writer(filters).writeValue(response.getWriter(), obj);
            }
        } catch (IOException var7) {
            LOG.error("[写json时候IO异常] " + obj, var7);
        }

    }
*/
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Cdn-Src-Ip");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }

    public static String getClientIp(HttpServletRequest request) {
        String clientIp = getIpAddr(request);
        return StringUtils.isNotBlank(clientIp) ? clientIp.split(",")[0] : null;
    }

    public static String getCurrentURL(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        if (request.getQueryString() != null) {
            url.append('?');
            url.append(request.getQueryString());
        }

        return url.toString();
    }

    public static String getEquipType(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (StringUtils.isNotBlank(userAgent)) {
            if (userAgent.contains("Android")) {
                return "Android";
            }

            if (userAgent.contains("IPhone")) {
                return "IPhone";
            }

            if (userAgent.contains("IPad")) {
                return "IPad";
            }

            if (userAgent.contains("Windows Phone")) {
                return "Windows Phone";
            }

            if (userAgent.contains("IPod")) {
                return "IPod";
            }
        }

        return "pc";
    }

    public static boolean isAjax(HttpServletRequest request) {
        return request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString());
    }

    public static boolean isPad(HttpServletRequest request) {
        String ua = request.getHeader("user-agent");
        return StringUtils.isNotBlank(ua) && (ua.contains("Android") || ua.contains("iPad") || ua.contains("Linux"));
    }

    private static String encode(String json) {
        return json.replaceAll("\"", "\\&").replaceAll(",", "\\");
    }

    private static String decode(String json) {
        return json.replaceAll("\\&", "\"").replaceAll("\\&", ",");
    }

    public static String getRequestJsonString(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();

        try {
            BufferedReader reader = request.getReader();
            char[] buff = new char[1024];

            int len;
            while((len = reader.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
        } catch (IOException var5) {
            var5.printStackTrace();
        }

        return sb.toString();
    }
}

